/***************************************************************************
 *   This is a part of the NextCAD Web APP.                                *
 *   Copyright (C) AMCAX, All rights reserved.                             *
 ***************************************************************************/

import { pickedFaceData, pickedLineData, pickedVertexData } from '@amcax/base';
import { PickInputRJSFFormat } from '@app-cad/common/components/command-form/constants';
import { NonDialogPickableCommandForm } from '@app-cad/common/components/command-form/pickable';
import { useTools } from '@app-cad/common/hooks/useTools';
import { wsApi } from '@app-cad/server';
import { RJSFSchema } from '@rjsf/utils';
import { useAsyncEffect } from 'ahooks';
import { isEmpty } from 'lodash';
import { useEffect, useState } from 'react';
import { useCommand } from '@app-cad/common/hooks/useCommand';
import { getIdOfPickedObj } from '@app-cad/common/utils/render';

import { ChildLineCommandProps } from './type';

type pickedALLType = pickedFaceData | pickedLineData | pickedVertexData;

type FormDataType = {
  obj: pickedALLType[];
  startPoint: pickedVertexData;
  endPoint: pickedVertexData;
  keepSrc: boolean;
};

export function MovePoint({
  onClose,
  props,
  editDxid,
  base,
}: ChildLineCommandProps) {
  const { picker } = useTools();

  const initData = {
    obj: undefined,
    startPoint: null,
    endPoint: null,
    keepSrc: true,
  };

  const [formData, setFormData] = useState<FormDataType>(initData);

  useEffect(() => {
    preview();
  }, [formData]);

  useAsyncEffect(async () => {
    if (props) {
      const obj = props?.params?.base;
      const startPoint = props?.params?.start;
      const endPoint = props?.params?.end;

      const keepSrc = props?.params?.keepSrc;
      await initEditDependency([obj, startPoint, endPoint]);
      const defaultObj = obj
        ? (picker.generatePickObjByPickID(obj) as pickedALLType)
        : undefined;
      const defaultStart = startPoint
        ? (picker.generatePickObjByPickID(startPoint) as pickedVertexData)
        : undefined;
      const defaultEnd = endPoint
        ? (picker.generatePickObjByPickID(endPoint) as pickedVertexData)
        : undefined;
      setFormData({
        obj: [defaultObj],
        startPoint: defaultStart,
        endPoint: defaultEnd,
        keepSrc: keepSrc,
      });
    } else {
      const defaultObj = base
        ? (picker.generatePickObjByPickID(base) as pickedALLType)
        : undefined;
      setFormData({
        ...initData,
        ...(defaultObj ? { obj: [defaultObj] } : {}),
      });
    }
  }, [editDxid, base]);

  const checkAndFinishDraw = async () => {
    const { obj, startPoint, endPoint } = formData;
    if (isEmpty(obj) || isEmpty(startPoint) || isEmpty(endPoint)) {
      return;
    }

    excute(false);
    onClose();
  };

  const excute = async (preview: boolean) => {
    const { obj, startPoint, endPoint, keepSrc } = formData;

    const params = {
      mode: 'point',
      start: getIdOfPickedObj(startPoint),
      end: getIdOfPickedObj(endPoint),
      keepSrc: keepSrc,
    };

    if (editDxid) {
      const res = await wsApi.setParams(editDxid, params, preview);
      if (preview) {
        previewInCommand(res);
      }
    } else {
      await confirmCommand(
        {
          a: params,
          o: obj.map((i) => getIdOfPickedObj(i)),
        },
        preview,
      );
    }
  };

  const preview = async () => {
    const { obj, startPoint, endPoint } = formData;
    clear();
    if (isEmpty(obj) || isEmpty(startPoint) || isEmpty(endPoint)) {
      return;
    }

    excute(true);
  };

  const isFormDataValid = () => {
    const { obj, startPoint, endPoint, keepSrc } = formData;
    return (
      !isEmpty(obj) &&
      startPoint !== null &&
      endPoint !== null &&
      keepSrc !== null
    );
  };

  const schema: RJSFSchema = {
    type: 'object',
    properties: {
      obj: {
        type: 'array',
        items: {
          type: 'string',
          enum: [],
        },
        format: PickInputRJSFFormat.MultiPickALL,
        uniqueItems: true,
      },
      startPoint: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      endPoint: {
        type: 'string',
        format: PickInputRJSFFormat.PickVertex,
      },
      keepSrc: {
        type: 'boolean',
        title: '显示初始元素',
        default: true,
      },
    },
  };

  const {
    initEditDependency,
    initingEdit,
    clear,
    confirmCommand,
    isLoading,
    previewInCommand,
  } = useCommand('cmd-move-point', {
    commandName: 'Translation',
    editDxid: editDxid || props?.shape,
    onClose,
    finishDraw: checkAndFinishDraw,
  });

  return (
    <NonDialogPickableCommandForm
      disabled={initingEdit}
      onCancel={onClose}
      submitLoading={isLoading}
      schema={schema}
      formData={formData}
      onChange={(v) => {
        setFormData({
          obj: v?.obj,
          startPoint: v.startPoint,
          endPoint: v.endPoint,
          keepSrc: v.keepSrc,
        });
        // setObj(v?.obj);
      }}
      extraUiSchema={{
        obj: {
          'ui:placeholder': '请输入元素',
          'ui:autofocus': !editDxid,
          'ui:disabled': !!editDxid,
        },
        startPoint: {
          'ui:placeholder': '请输入起点',
          'ui:autofocus': !!editDxid,
        },
        endPoint: {
          'ui:placeholder': '请输入终点',
        },
      }}
      submitText='完成'
      onSubmit={checkAndFinishDraw}
      isFormDataValid={isFormDataValid()}
    />
  );
}
